package com.topisv.tms.web.work;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.topisv.tms.entity.User;
import com.topisv.tms.entity.work.WorkBatch;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.service.account.AccountService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.work.WorkBatchService;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.utils.JsonUtil;

/**
 * 作业任务_control
 * @author ch
 */
@Controller
@RequestMapping({ "/workTask" })
public class WorkTaskController {

	private static final Logger logger = LoggerFactory.getLogger(WorkTaskController.class);

	@Autowired
	private WorkBatchService workBatchService;
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private WorkTaskService workTaskService;
	@Autowired
	private AccountService accountService;
	
	
	/**
	 * 导向创建任务页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "v2_toCreateWorkTask/{batchCode}", method = RequestMethod.GET)
	public String toCreateWorkTask(@PathVariable("batchCode") String batchCode, Model model) {
		try {

			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		    String customerCode=curUser.customerCode;
			
		    //作业批次
			WorkBatch workBatch=this.workBatchService.loadWorkBatchByCode(batchCode);
			model.addAttribute("batch",workBatch);
			
			//查询未处理订单
			Map<String, Object> param=new HashMap<String, Object>();
			param.put("batchCode", batchCode);
			param.put("cancelStatus", "ok");
			param.put("status", "1");  //订单状态 (1.创建批次 2.创建任务 3.已拣货  4.已灯光拣选  9.待包装   5.已包装  6.已发货  7.已签收  8.异常 )
			List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
			model.addAttribute("orderList",orderList);
			
			//查询已生成的任务
			List<WorkTask> taskList=this.workTaskService.loadTaskByBatchCode(batchCode);
			model.addAttribute("taskList",taskList);
			
			//商家用户
			List<User> userList=this.accountService.loadCustomerTypeUser("customer", customerCode);
			model.addAttribute("userList", userList); 
			
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return "work/createTask/createWorkTask";
	}

	/**
	 * 创建作业任务预览
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "v2_preWorkTask", method = RequestMethod.POST)
	public String preWorkTask(ServletRequest request,HttpServletResponse response,Model model) {
		try {
			String tactics=request.getParameter("tactics");  //策略
			Integer taskcount=Integer.valueOf((StringUtils.isEmpty(request.getParameter("taskcount"))?"0":request.getParameter("taskcount"))); //任务容量
			String batchCode=request.getParameter("batchCode"); //任务批次
			String pickType=request.getParameter("pickType"); //任务类型 (single 单件 mulit: 多件)
			
			//作业批次
			WorkBatch workBatch=this.workBatchService.loadWorkBatchByCode(batchCode);
			model.addAttribute("batch",workBatch);
			
			//待处理订单
	 		Map<String, Object> param=new HashMap<String, Object>();
	 		param.put("batchCode", batchCode);
	 		param.put("cancelStatus", "ok");
	 		param.put("status", "1"); //订单状态 (1.创建作业批次 2.创建作业任务 3.已拣货 4.已包装 5.已发货 6.已签收 7.异常登记)
	 		List<WorkOrder> orderList=this.workOrderService.loadOrder(param);
	 		
	 		//已创建任务
	 		List<WorkTask> taskList=null;
	 		if("single".equals(pickType)){
	 			taskList=this.workTaskService.createTask_single(orderList,workBatch,tactics,taskcount==0?orderList.size():taskcount);
	 	 		model.addAttribute("taskList",taskList);
	 	 		return "work/createTask/preWorkTask_single";
	 		}
	 		else if("multi".equals(pickType)){
	 			Map<Object, Object> map=this.workTaskService.createTask_multi(orderList,workBatch,tactics,taskcount==0?orderList.size():taskcount);
	 	 		model.addAttribute("taskList",map.get("workList"));
	 	 		model.addAttribute("skuList",map.get("skuList"));
	 	 		return "work/createTask/preWorkTask_multi";
	 		}
		
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return null;
	}
	/**
	 * 
	 * */
	@RequestMapping(value = "ajaxBackUnhandleOrder")
	@ResponseBody
	public synchronized void ajaxBackUnhandleOrder(ServletRequest request,HttpServletResponse response) {
		String orderno=request.getParameter("orderno");  //批次号
		PrintWriter out=null;
		JSONObject json=null;
		String result = "success";
		try{
			out = response.getWriter();
			json = new JSONObject();
			
			result = this.workTaskService.backUnhandleOrder(orderno);
			
		}catch(PaiUException e){
			logger.info("", e);
			result = e.getErrorCode();
			if("C001".equals(result)){
				result = "cancel";
			}else if("C002".equals(result)){
				result = "back";
			}
		}catch(Exception e){
			logger.info("", e);
			result = "error";
		}
		json.put("result", result);
		out.print(json);
	}
	/**
	 * 创建作业任务
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "ajaxCreateTask")
	@ResponseBody
    public String ajaxCreateTask(ServletRequest request, HttpServletResponse response) {
	    String batchCode = request.getParameter("batchCode"); // 批次号
	    String workOrderJsonText = request.getParameter("workOrderJsonText");
	    String pickModel = request.getParameter("pickModel"); // 拣货模式, ( lamp: 灯光拣选 car: 推车拣选 )

	    boolean isLockSuccess = false;
	    
	    try {
	        /** begin add  防止重复操作的校验. 20160921, lianghe.yuan */
            isLockSuccess = workTaskService.lock("ajaxCreateTask", batchCode, "-");
            
            if (!isLockSuccess) {
                return "false";
            }
            /** begin end  防止重复操作的校验. 20160921, lianghe.yuan */
            
            JSONArray infoArray = JSONArray.fromObject(workOrderJsonText);
            
            Map<String, String> stockMap = new HashMap<String, String>();
            Map<String, Integer> ranknoMap = new HashMap<String, Integer>();
            
            for (Object info : infoArray) {
                Map<String, Object> map = (Map<String, Object>)info;
                String ordeno = (String)map.get("ordeno");
                String stockInfo = (String)map.get("stockInfo");
                Integer rankno = Integer.valueOf(map.get("rankno") + "");
                
                stockMap.put(ordeno, stockInfo);
                ranknoMap.put(ordeno, rankno);
            }

            boolean result = this.workTaskService.createTask(stockMap, ranknoMap, batchCode, pickModel);
            return result ? "true" : "false";

        } catch (Exception e) {
            logger.error("批次创建任务失败，批次号：{}", batchCode, e);
            
            try {
                this.workTaskService.rollbackCusStockTask(batchCode);
            } catch (Exception ex) {
                logger.error("回滚库存异常，需手工操作数据库进行回滚。 批次号: {}。", batchCode, ex);
            }
            
            return "false";
            
        } finally {
            if (isLockSuccess) {
                // add 防止重复操作的校验. 操作完成，释放锁. 20160921, lianghe.yuan
                workTaskService.releaseLock("ajaxCreateTask", batchCode);
            }
        }
    }
	
	/**
	 * 指派任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxCommandTask")
	public String ajaxCommandTask(ServletRequest request,HttpServletResponse response) {
		try {
			String jobuuid=request.getParameter("jobuuid");
			Long taskId=Long.valueOf(request.getParameter("taskId"));
			String result=this.workTaskService.commandPickTask(taskId,jobuuid);
			
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("msg", result);
			String json = JsonUtil.getObjectString(map);
			PrintWriter out;
			out = response.getWriter();
			out.print(json);
		} catch (Exception e) {
			
			logger.error("error",e);
		}
		return null;
	}
	
}